/**
 *
 * MTG Life Counter
 * Game state class
 *
 * Created by Nathan Black
 */

#import "LifeCounterGame.h"

static NSString *s_gameStatePath = @"/var/root/Library/LifeCounter/gamestate";

@implementation LifeCounterGame

-init 
{
    @try {
        if ([[NSFileManager defaultManager] fileExistsAtPath:s_gameStatePath]) {
            NSLog(@"gamestate file does exist");
            LifeCounterGame *game = [NSKeyedUnarchiver unarchiveObjectWithFile:s_gameStatePath];
            if (game == NULL) {
                NSLog(@"--== Failed to unarchive gamestate object! ==--");
                [NSException raise:@"LifeCounterIOException" format:@"unarchived object was null"];
            }

            self = [game retain];
        }
        else {
            [NSException raise:@"FileNotFoundException" format:@"file doesn't exist"];
        }
    }
    @catch (NSException* ex) {
        NSLog(@"Caught exception: %@, reason: %@", [ex name], [ex reason]);
        if ((self = [super init])) {
            [self newGame];
        }
    }
    
    return self;
}

- (id)initWithCoder:(NSCoder *)coder 
{ 
    self = [super init]; 
    NSLog(@"initWithCoder");
    NSArray* lifeTotalsArray = [[coder decodeObjectForKey:@"LifeTotals"] autorelease]; 

    NSLog(@"decoded lifeTotalsArray: 0x%8lx", lifeTotalsArray);
    if (lifeTotalsArray != NULL && [lifeTotalsArray count] == 2) {
        _lifeTotals[0] = [(NSNumber*)[lifeTotalsArray objectAtIndex:0] intValue];
        _lifeTotals[1] = [(NSNumber*)[lifeTotalsArray objectAtIndex:1] intValue];
        NSLog(@"done retrieving life totals: %d", _lifeTotals[0]);
    }
    else {
        NSLog(@"Error decoding LifeTotals array");
        [self newGame];
    }

    return self; 
}

- (void)encodeWithCoder:(NSCoder *)coder 
{
    NSArray* lifeTotalsArray = [NSArray arrayWithObjects:
        [NSNumber numberWithInt:_lifeTotals[0]], 
        [NSNumber numberWithInt:_lifeTotals[1]], NULL];
    
    [coder encodeObject:lifeTotalsArray forKey:@"LifeTotals"];
}

- (BOOL)save
{
    if ([NSKeyedArchiver archiveRootObject:self toFile:s_gameStatePath]) {
        NSLog(@"game state saved successfully");
        return true;
    }
    else {
        NSLog(@"--== game state failed to save! ===--");
        return false;
    }
}

- (int)numberOfPlayers
{
    return 2;
}

- (void)lifeChangeWithPlayer:(int)player delta:(int)delta
{
    _lifeTotals[player] += delta;
}

- (int)playerLife:(int)player
{
    return _lifeTotals[player];
}

- (void)newGame
{
    _lifeTotals[0] = 20;
    _lifeTotals[1] = 20;
    
    [[NSFileManager defaultManager] removeFileAtPath:s_gameStatePath handler:NULL];
}

@end